package org.javaweb.cms_web.service;

import org.javaweb.cms_web.mapper.ArticleManagementMapper;
import org.javaweb.cms_web.model.Article;
import org.javaweb.cms_web.model.ArticleDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
public class ArticleManagementService {

    @Autowired
    private ArticleManagementMapper articleManagementMapper;


    //处理链接的
    public String prepareUrl(String originalPath) {
        if (originalPath == null || originalPath.isEmpty()) {
            return "";
        }

        // 将反斜杠替换为正斜杠
        String normalizedPath = originalPath.replace("\\", "/");
        try {
            // 对路径进行 URL 编码
            return URLEncoder.encode(normalizedPath, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    // 根据团队ID查询所有文章
    public List<ArticleDTO> getArticlesByTeam(int teamID) {
        return articleManagementMapper.findArticlesByTeam(teamID);
    }

    // 根据团队ID和文章标题模糊查询文章
    public List<ArticleDTO> getArticlesByTeamAndTitle(int teamID, String title) {
        return articleManagementMapper.findArticlesByTeamAndTitle(teamID, "%" + title + "%");
    }

    // 根据文章ID查询单篇文章
    public ArticleDTO getArticleById(int articleID) {
        return articleManagementMapper.findArticleById(articleID);
    }

    // 获取所有文章
    public List<ArticleDTO> getAllArticles() {
        return articleManagementMapper.findAllArticles();
    }

    // 保存新文章
    public boolean saveArticle(ArticleDTO article) {
        return articleManagementMapper.insertArticle(article) > 0;
    }

    // 根据ID获取文章
    public ArticleDTO getArticleById(Integer articleId) {
        return articleManagementMapper.findArticleById(articleId);
    }

    // 更新文章
    public boolean updateArticle(ArticleDTO article) {
        return articleManagementMapper.updateArticle(article) > 0;
    }

    // 删除文章
    public boolean deleteArticle(Integer articleId) {
        return articleManagementMapper.deleteArticle(articleId) > 0;
    }

    // 根据搜索和筛选条件获取文章
    public List<ArticleDTO> getFilteredArticles(String searchKeyword, String startDate, String endDate) {
        return articleManagementMapper.findArticlesByConditions(searchKeyword, startDate, endDate);
    }

    public List<ArticleDTO> getPendingArticles() {
        return articleManagementMapper.findArticlesByStatus(0);
    }

    public boolean updateStatus(Integer articleId, Integer status) {
        return articleManagementMapper.updateStatus(articleId, status) > 0;
    }

    public boolean updateRejectReason(Integer articleId, String rejectReason) {
        return articleManagementMapper.updateRejectReason(articleId, rejectReason) > 0;
    }
}
